<?php


namespace app\common\lib;


class SetArray
{
    /**
     * 按父子排序 3级分类
     * @param $data
     * @return array
     */
    public static function childrenAfterParent3($data) {
        $arr = [];
        foreach ($data as $k=>$v) {
            if ($v['parent_id'] == 0) {
                $v['level'] = 0;
                $arr[] = $v;
                foreach ($data as $k1=>$v1) {
                    if ($v1['parent_id'] == $v['id']) {
                        $v1['level'] = 1;
                        $arr[] = $v1;
                        foreach ($data as $k2=>$v2) {
                            if ($v2['parent_id'] == $v1['id']) {
                                $v2['level'] = 2;
                                $arr[] = $v2;
                            }
                        }
                    }
                }
            }
        }
        return $arr;
    }

    /**
     * 分类树， 支持无限极分类
     */
    public static function getTree($data)
    {
        $items = [];
        foreach ($data as $v) {
            $items[$v['id']] = $v;
        }
        $tree = [];
        foreach ($items as $id => $item) {
            if (isset($items[$item['parent_id']])) {
                $items[$item['parent_id']]['list'][] = &$items[$id];
            } else {
                $tree[] = &$items[$id];
            }
        }
        return $tree;
    }
    /**
     * 按父子排序 2级分类
     * @param $data
     * @return array
     */
    public static function childrenAfterParent2($data) {
        $arr = [];
        foreach ($data as $k=>$v) {
            if ($v['parent_id'] == 0) {
                $v['level'] = 0;
                $arr[] = $v;
                foreach ($data as $k1=>$v1) {
                    if ($v1['parent_id'] == $v['id']) {
                        $v1['level'] = 1;
                        $arr[] = $v1;
                    }
                }
            }
        }
        return $arr;
    }

    public static function arrsSortByKey($result, $key, $sort = SORT_DESC) {
        if(!is_array($result) || !$key) {
            return [];
        }
        array_multisort(array_column($result, $key), $sort, $result);
        return $result;
    }
}